// pages/towxml/index.js
const app = getApp();

import DB from '../../utils/db';


const exportHtmlToDocx = async (htmlContent, fileName = 'exported-document.docx') => {
  try {
    const result = await wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'word',
        html: htmlContent,
        fileName: fileName
      }
    });
    // console.log(result.result.fileID)
    wx.cloud.downloadFile({
      fileID: result.result.fileID,
      success (res) {
        // console.log(res)
        if (res.statusCode === 200) {
          wx.showModal({
            title: '保存成功',
            content: `部分手机存在打开空白文件,请通过微信文件助手发到电脑查看。`,
            showCancel: false,
            confirmText: '我知道了', // 确认按钮的文字
            success: function (res1) {
              if (res1.confirm) {
                wx.hideLoading();
                console.log('用户点击确定') // 用户点击确定后的操作
                wx.openDocument({
                  filePath: res.tempFilePath,
                  fileType: 'docx',
                  showMenu:true, //关键点
                })
              }
            }
          })
        }       
      }
    })
    

  } catch (error) {
    wx.hideLoading();
    console.error('导出过程中出错:', error);
    wx.showToast({
      title: '导出失败',
      icon: 'none',
      duration: 2000
    });
  }
};

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  pdf(){
    
    wx.showLoading({
      title: '导出中',
     })

    // exportHtmlToDocx(this.data.md, '我的文档.docx')
    
    this.generateDocx()
  },

  // 调用云函数生成文档
  generateDocx() {
    // console.log(this.data.record)
    wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
            type:'pdf',
            record:this.data.record
        },
        success: (res) => {
            if (res.result.success) {
                this.setData({ fileID: res.result.fileID });
                this.downloadFile(res.result.fileID); // 下载文件
            } else {
                wx.showToast({
                    title: '生成失败: ' + res.result.error,
                    icon: 'none',
                });
            }
        },
        fail: (err) => {
            wx.showToast({
                title: '云函数调用失败',
                icon: 'none',
            });
            console.error(err);
        },
    });
},

// 下载文件
downloadFile(fileID) {
    wx.cloud.downloadFile({
        fileID,
        success: (res) => {
          wx.hideLoading();
            const filePath = res.tempFilePath;
            wx.openDocument({
                filePath,
                fileType: 'docx',
                showMenu:true, //关键点
                success: () => {
                  wx.cloud.deleteFile({
                  fileList: [fileID], // 要删除的文件ID列表
                  success: (res) => {
                      console.log('云文件删除成功', res);
                      wx.showToast({ title: '文件已删除', icon: 'success' });
                  },
              });
            }
            });
        },
        fail: (err) => {
            wx.showToast({ title: '下载失败', icon: 'none' });
            console.error(err);
        },
    });
},

  selectCreateResume(){
    // console.log(this.data.openId)
    DB.select('selectCreateResume', this.data.openId).then((resp) => {
      // console.log(resp)
      this.setData({
        record: resp.result,
        fileID: resp.result.personalKeyInformation.img
      });
      wx.cloud.getTempFileURL({
        fileList: [{
          fileID: resp.result.personalKeyInformation.img,
          maxAge: 60 * 60, // one hour
        }]
      }).then(res => {
        this.setData({
          'record.personalKeyInformation.img': res.fileList[0].tempFileURL,
        });
        this.markdown(resp.result)
        wx.hideLoading();
      })
    }).catch(() => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },

  markdown(record) {
    // console.log(record.personalKeyInformation.img)
    let img = ''
    
    let personalKeyInformation = ''
    let evaluation = ''
    let education = ''
    let workExperience = ''
    let project = ''
    let qualificationCertificate = ''
    // console.log(age)
    img = `${record.personalKeyInformation.img}`
    personalKeyInformation = `
    <table>
        <tr>
            <td style="width: 60%;">
              <div style="vertical-align: top;text-align: left;" >
                <div>
                  <div style="margin-bottom:10px;font-size:26px;font-weight:bold;"> ${record.personalKeyInformation.userText}</div>
                  <div style="margin-bottom:10px;"><strong>年龄:</strong> ${record.personalKeyInformation.birthText}</div>
                  <div style="margin-bottom:10px;"><strong>电话:</strong> ${record.personalKeyInformation.phone}</div>
                  <div style="margin-bottom:10px;"><strong>性别:</strong> ${record.personalKeyInformation.genderText}</div>
                  <div style="margin-bottom:10px;"><strong>邮箱:</strong> ${record.personalKeyInformation.email}</div>
                  <div style="margin-bottom:10px;"><strong>应聘岗位:</strong> ${record.personalKeyInformation.postText}</div>
                </div>
              </div>
            </td>
            <td style="width: 40%;">
            <div><img src="${record.personalKeyInformation.img}" style="vertical-align: top; "></div>
            </td>
        </tr>
    </table>
    `
    evaluation = `
    ${record.evaluation.evaluation}
    `
    for(var j = 0; j < record.education.length; j++){
      education += `
                    <div style="margin-bottom:5px;">
                        <div style="font-weight:bold;margin-bottom:5px;">
                <span style="font-weight:bold;">${record.education[j].schoolText} </span>&nbsp;&nbsp;
                <span style="font-size:14px;font-weight:normal">${record.education[j].enrolText}-${record.education[j].graduateText}</span>
              </div>
                        <div>${record.education[j].majorText} / ${record.education[j].educationText}</div>
                        ${record.education[j].subject}
                    </div>` 
    };
    for(var j = 0; j < record.workExperience.length; j++){
      workExperience += `
      <div style="margin-bottom:5px;">
                <div style="font-weight:bold;margin-bottom:5px;">
                    <span style="font-weight:bold;">${record.workExperience[j].companyText}</span> - 
                    <span style="font-style:italic;">${record.workExperience[j].postText}</span>&nbsp;&nbsp;
        <span style="font-size:14px;font-weight:normal">${record.workExperience[j].entryText}-${record.workExperience[j].resignText}</span>
                </div>
                ${record.workExperience[j].workContent}
            </div>` 
    };
    for(var j = 0; j < record.project.length; j++){
      project += `
      <div style="margin-bottom:5px;">
                <div style="font-weight:bold;margin-bottom:5px;">
                    <span style="font-weight:bold;">${record.project[j].projectText}</span> - 
                    <span style="font-style:italic;">${record.project[j].roleText}</span>&nbsp;&nbsp;
        <span style="font-size:14px;font-weight:normal">${record.project[j].entryText}-${record.project[j].resignText}</span>
                </div>
      
                ${record.project[j].projectContent}
            </div>` 
    };
    for(var j = 0; j < record.qualificationCertificate.length; j++){
      qualificationCertificate += `
      ${record.qualificationCertificate[j].certificate}` 
    };

    const contentMd =`<!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="font-family:'Microsoft YaHei',Arial,sans-serif;width:550px;background-color:white;box-shadow:0 0 10px rgba(0,0,0,0.1);display:flex;">
    <div style="font-size:26px;font-weight:bold;text-align: center; color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">
			    个人简历
			</div>
            <!-- 左侧内容区 -->
            <div style="padding:30px;">
                <!-- 头部信息 -->        
                <div style="margin-bottom:25px;">
                   
                    ${personalKeyInformation}
                </div>    
                
                <!-- 自我评价 -->
                <div style="margin-bottom:25px;">
                    <div style="font-size:18px;font-weight:bold;color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">自我评价</div>
                    ${evaluation}
                </div>
                
                <!-- 教育背景 -->
                <div style="margin-bottom:25px;">
                <div style="font-size:18px;font-weight:bold;color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">教育背景</div>
                ${education}
                </div>
                
                <!-- 工作经历 -->
                <div style="margin-bottom:25px;">
                    <div style="font-size:18px;font-weight:bold;color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">工作经历</div>
                    ${workExperience}
                </div>

                <!-- 项目经历 -->
                <div style="margin-bottom:25px;">
                    <div style="font-size:18px;font-weight:bold;color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">项目经历</div>
                    ${project}
                </div>
                
                <!-- 职业技能 -->
                <div style="margin-bottom:25px;">
                    <div style="font-size:18px;font-weight:bold;color:#1e88e5;border-bottom:2px solid #1e88e5;padding-bottom:5px;margin-bottom:15px;">职业技能</div>
                    ${qualificationCertificate}
                </div>
            </div>
    </body>
    </html>
        `
        // console.log(contentMd)

 
    let result = app.towxml(contentMd, 'html', {
      theme: 'light'
    });
    // console.log(result)
    this.setData({
        content: result,
        md:contentMd
    });
     
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      'openId': wx.getStorageSync("openId")
    })
    // this.setData({
    //   'openId': 'oIdmn7SO1Q4yHXuhJF9Gc27FYztI'
    // })
    wx.showLoading({
      title: '数据加载中...', // 这里设置提示词
      mask: true // 显示透明蒙层
    });
   
    this.selectCreateResume()
    
    // this.markdown()
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})